﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DictationManager;
using System.Configuration;

namespace MedicalDictationView
{
    public partial class MainIU : Form
    {
        CoreManager _manager;
        Guid _currentGuid;
        String[] DictationInfo;
        bool IsCompleted;
        bool _dictationMode;
        bool _blockUI;

        public delegate void CloseHandler(object sender, CloseArgs args);
        public event CloseHandler dictationClosed;

        public MainIU()
        {
            _blockUI = false;
            InitializeComponent();
            try
            {
                _manager = new CoreManager();
                _manager.dictationLoaded += new CoreManager.LoadingHandler(_manager_dictationLoaded);
                _manager.deviceConnection += new CoreManager.LoadingHandler(_manager_deviceConnection);
                _manager.EOLButtonPressed += new CoreManager.EOLHandler(_manager_EOLButtonPressed);
                _manager.fileNotFound += new CoreManager.NoFileFoundHandler(_manager_fileNotFound);
                DictationTimer.Interval = 100;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void _manager_EOLButtonPressed(object sender, LoadArgs args)
        {
            BtnSave1_Click(sender, new System.EventArgs());
        }

        public void LoadDictation(String[] DictationParameters, bool IsNew)
        {
            // Dictation Mode = 0 -> All access
            _dictationMode = bool.Equals(DictationParameters[1], "0");
            DictationInfo = DictationParameters;
            if (_manager.ExistPreviousDictation)
            {
                this.TopMost = false;
                if (MessageBox.Show("You have a previous dictation. Do you want to save it?", "Medical Dictation", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    _manager.SaveDictation();
                }
                else
                {
                    _manager.DiscardDictation();
                }
                this.TopMost = true;
            }
            _manager.LoadDictation(DictationInfo, IsNew);
            IsCompleted = false;
        }

        void _manager_deviceConnection(object sender, LoadArgs args)
        {
            if (_dictationMode)
                BtnRecord1.Enabled = true;
        }

        void _manager_dictationLoaded(object sender, LoadArgs args)
        {
            lblSoundLength.Text = MilisecondsToString(args.length);
            FileTrackBar.Maximum = args.length;
            LoadUI();
            if (!_dictationMode)
                _manager.GoToStart();
            DictationTimer.Start();
        }

        void _manager_fileNotFound(object sender, FileArgs args)
        {
            DictationTimer.Stop();
            MessageBox.Show("File not found: \n" + args.fileName, "Handler");
            btnCreate.Enabled = false;
            BtnFForward.Enabled = false;
            BtnFRewind.Enabled = false;
            BtnPlay1.Enabled = false;
            BtnRecord1.Enabled = false;
            BtnSave.Enabled = false;
            BtnStop1.Enabled = false;
            btnVolume.Enabled = false;
            _dictationMode = false;
            _blockUI = true;
        }

        private void LoadUI()
        {
            if (DictationInfo != null)
            {
                for (int i = 2; i < DictationInfo.Length; i++)
                    if (DictationInfo[i] == null)
                        DictationInfo[i] = "";
                lblPID.Text = DictationInfo[2];
                lblNomPatient.Text = DictationInfo[3];
                lblAcNum.Text = DictationInfo[4];
                lblNomEstudio.Text = DictationInfo[5];
                lblNomRadiologo.Text = DictationInfo[6];
                lblFechaHoraAdmision.Text = DictationInfo[7];
                if (_dictationMode)
                    BtnRecord1.Enabled = _manager.IsDeviceRecordConnected();
            }
        }

        private void CleanUI()
        {
            if (DictationInfo != null)
            {
                lblPID.Text = String.Empty;
                lblNomPatient.Text = String.Empty;
                lblAcNum.Text = String.Empty;
                lblNomEstudio.Text = String.Empty;
                lblNomRadiologo.Text = String.Empty;
                lblFechaHoraAdmision.Text = String.Empty;
                lblSoundLength.Text = "00:00";
                lblSoundPosition.Text = "00:00";
            }
        }

        private string MilisecondsToString(int p)
        {
            p = p / 1000;
            return String.Format("{0:00}:{1:00}:{2:00}", p / 3600, (p % 3600) / 60, (p % 3600) % 60);
        }

        private void MainIU_Load(object sender, EventArgs e)
        {
            if (ConfigurationManager.AppSettings["DebugMode"].ToUpper().Equals("TRUE"))
            {
                btnCreate.Visible = true;
                BtnLoad.Visible = true;
                Separator1.Visible = true;
            }
        }

        private void DictationTimer_Tick(object sender, EventArgs e)
        {
            lblSoundPosition.Text = MilisecondsToString(_manager.currentPosition);
            lblSoundLength.Text = MilisecondsToString(_manager.fileLength);

            int position = _manager.currentPosition;
            int size = _manager.fileLength;

            try
            {
                if (size < position)
                {
                    FileTrackBar.Maximum = position;
                    FileTrackBar.Value = position;
                }
                else
                {
                    FileTrackBar.Maximum = size;
                    FileTrackBar.Value = position;
                }
            }
            catch(Exception ex)
            {
                FileTrackBar.Maximum = position;
                FileTrackBar.Value = position;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            _currentGuid = Guid.NewGuid();
            _manager.LoadDictation(new string[] { _currentGuid.ToString() }, true);
        }

        private void BtnLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog tmpDialog = new OpenFileDialog();
            tmpDialog.Filter = "WAV Files (*.wav)|*.wav|MP3 Files (*.mp3)|*.mp3|All Files (*.*)|*.*";
            tmpDialog.ShowDialog();
            if (tmpDialog.FileName != string.Empty)
            {
                _manager.LoadDictation(new string[] { tmpDialog.FileName }, false);
            }
        }

        private void BtnStop1_Click(object sender, EventArgs e)
        {
            _manager.EventButton("Stop", "Pressed");
        }

        private void BtnPlay1_Click(object sender, EventArgs e)
        {
            _manager.EventButton("Play", "Pressed");
        }

        private void BtnRecord1_Click(object sender, EventArgs e)
        {
            if (_dictationMode)
            {
                _manager.EventButton("Record", "Pressed");
            }
        }

        private void BtnFRewind_MouseDown(object sender, MouseEventArgs e)
        {
            _manager.EventButton("FRewind", "Pressed");
        }

        private void BtnFRewind_MouseUp(object sender, MouseEventArgs e)
        {
            _manager.EventButton("FRewind", "Released");
        }

        private void BtnFForward_MouseUp(object sender, MouseEventArgs e)
        {
            _manager.EventButton("FForward", "Released");
        }

        private void BtnFForward_MouseDown(object sender, MouseEventArgs e)
        {
            _manager.EventButton("FForward", "Pressed");
        }

        private void btnVolume_Click(object sender, EventArgs e)
        {
            VolumeForm speakerVol = new VolumeForm(new Point(this.Location.X + this.Width + 10, this.Location.Y), 100, _manager.outputVolume);
            speakerVol.eventVolume += new VolumeForm.volumeHandler(speakerVol_eventVolume);
            speakerVol.Show();
        }

        void speakerVol_eventVolume(object sender, volumeArgs args)
        {
            _manager.outputVolume = args.Value;
        }

        private void BtnSave1_Click(object sender, EventArgs e)
        {
            if (_manager.fileLength > 0)
            {
                _manager.SaveDictation();
                IsCompleted = true;
            }
            this.Close();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            _currentGuid = Guid.NewGuid();
            _manager.LoadDictation(new string[] { _currentGuid.ToString() }, true);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            VolumeForm micVol = new VolumeForm(new Point(0, 0), 100, _manager.inputVolume);
            micVol.eventVolume += new VolumeForm.volumeHandler(micVol_eventVolume);
            micVol.Show();
        }

        void micVol_eventVolume(object sender, volumeArgs args)
        {
            _manager.inputVolume = args.Value;
            //this.BringToFront();
            this.Focus();
        }

        private void MainIU_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!_blockUI)
            {
                bool empty = false;
                this.TopMost = false;

                if (_manager.ExistPreviousDictation)
                {
                    empty = (_manager.SaveDictation());
                }
                if (dictationClosed != null)
                {
                    if (!empty)
                    {
#if DEBUG
                        MessageBox.Show(_manager.FileTargetPath, IsCompleted.ToString());
#endif
                        dictationClosed(this, new CloseArgs(_manager.FileTargetPath, IsCompleted));
                    }
                    else
                    {
#if DEBUG
                        MessageBox.Show(String.Empty, IsCompleted.ToString());
#endif
                        dictationClosed(this, new CloseArgs(String.Empty, IsCompleted));
                    }
                }
                _manager.FreeComponents();
            }
            else
            {
                _manager.FreeComponents();
                dictationClosed(this, new CloseArgs(String.Empty, IsCompleted));
            }
        }

        private void MainIU_Deactivate(object sender, EventArgs e)
        {
            this.Opacity = 0.85;
        }

        private void MainIU_Activated(object sender, EventArgs e)
        {
            this.Opacity = 1;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (_manager.fileLength > 0)
            {
                _manager.SaveDictation();
                IsCompleted = false;
            }
            this.Close();
        }
    }

    public class CloseArgs
    {
        string _filePath;
        bool _ToTranscribe;
        public CloseArgs(string path, bool toTranscribe)
        {
            _filePath = path;
            _ToTranscribe = toTranscribe;
        }

        public string FilePath
        {
            get { return _filePath; }
        }

        public bool ToTranscribe
        {
            get { return _ToTranscribe; }
        }
    }
}